const express = require('express');
const util = require('../common/util');

/**
 * 检查是否登录
 * @param {express.Request} req 
 * @param {express.Response} res 
 * @param {express.NextFunction} next 
 */
function isLogin(req, res, next){
    if (!req.session.isLogin){
        res.json(util.FormatJSONData(401,"无访问授限"));
    } else{
        next();
    }
}

/**
 * 检查是否是管理员
 * @param {express.Request} req 
 * @param {express.Response} res 
 * @param {express.NextFunction} next 
 */
function isAdmi(req,res,next){
    if (parseInt(req.session.user.role) !== 2){
        res.json(util.FormatJSONData(402,"无访问权限"));
    } else{
        next();
    }
}

/**
 * 检查是否是卖家或管理员
 * @param {express.Request} req 
 * @param {express.Response} res 
 * @param {express.NextFunction} next 
 */
function isSellerOrAdmi(req,res,next){
    let seller = (parseInt(req.params.seller || req.query.seller || req.body.seller || req.session.user.user_id));
    let id = parseInt(req.session.user.user_id);
    util.log("isSellerOrAdmi",seller,id);
    if (id === seller || parseInt(req.session.user.role) === 2){
        next();
    } else{
        util.err(`id:${id},seller${seller}`)
        res.json(util.FormatJSONData(402,"无访问权限"));
    }
}

/**
 * 检查是否是自己或管理员
 * @param {express.Request} req 
 * @param {express.Response} res 
 * @param {express.NextFunction} next 
 */
function isSelfOrAdmi(req,res,next){
    let user_id = (parseInt(req.params.user_id || req.query.user_id || req.body.user_id || req.session.user.user_id));
    let id = parseInt(req.session.user.user_id);
    if (id === user_id || parseInt(req.session.user.role) === 2){
        next();
    } else{
        util.log(`id:${id},user_id:${user_id}`)
        res.json(util.FormatJSONData(402,"无访问权限"));
    }
}

/**
 * 检查是否是自己
 * @param {express.Request} req 
 * @param {express.Response} res 
 * @param {express.NextFunction} next 
 */
function isSelf(req,res,next){
    let user_id = (parseInt(req.params.user_id || req.query.user_id || req.body.user_id));
    let id = parseInt(req.session.user.user_id);
    if (id === user_id){
        next();
    } else{
        util.err(`id:${id},user_id${user_id}`)
        res.json(util.FormatJSONData(402,"无访问权限"));
    }
}



module.exports = {
    isLogin,
    isAdmi,
    isSelfOrAdmi,
    isSellerOrAdmi,
    isSelf
};